import React from 'react';
import {
  AsyncStorage,
  Alert,
  Linking,
} from 'react-native';

import Config from '../config';
import Constants from '../common/Constants';
import BaseModelNew from './BaseModelNew';
import ToastUtils from '../common/ToastUtils';

export default class LoginModel extends BaseModelNew{
  constructor() {
    super();
    this.moduleType = Constants.MODULE_TYPE.LOGIN;
    this.sendLogin = this.sendLogin.bind(this);
    this.sendRequestSms = this.sendRequestSms.bind(this);
    this.updateAuthorization = this.updateAuthorization.bind(this);
    this.updateLoginType = this.updateLoginType.bind(this);
    this.checkAuthorization = this.checkAuthorization.bind(this);
    this.checkIsVisitor = this.checkIsVisitor.bind(this);
    this.checkIsUser = this.checkIsUser.bind(this);
    this.sendVisitorLogin = this.sendVisitorLogin.bind(this);
    this.getAutorization = this.getAutorization.bind(this);
    this.clearLoginData = this.clearLoginData.bind(this);
    this.sendRegiste = this.sendRegiste.bind(this);
    this.sendVerify = this.sendVerify.bind(this);
    this.checkVersion = this.checkVersion.bind(this);
    this._loginData = {};

    this._callback = null;
    this._dealCount = 2;
    this._needUpdate = false;
  }

  setup(callback, dataManager) {
    this._callback = callback;
    this.dataManager = dataManager;

    this.initProps();
    this.checkVersion();
  }

  getNeedUpdate() {
    return this._needUpdate;
  }

  _setupFinish() {
    this._dealCount -= 1;
    if(this._dealCount === 0) {
      this._callback();
    }
  }

  initProps() {
    AsyncStorage.getItem("loginData",function(errs,result){
              //TODO:错误处理
              if (!errs) {
                if(result == null) {
                  this._loginData.authorization = "0";
                  this._loginData.loginType = "none";
                }
                else {
                  let loginData = JSON.parse(result);
                  this._loginData = loginData;
                }
                console.log('Get loginData success', result);
              }
              else {
                this._loginData.authorization = "0";
                this._loginData.loginType = "none";
                console.log('Get loginData error');
              }
              this.dataManager.getModel(Constants.MODULE_TYPE.PUSH).addTag("loginType", this._loginData.loginType);
              this._setupFinish();
          }.bind(this));
  }

  //是否是登录状态
  checkAuthorization() {
    return this._loginData && this._loginData.authorization && this._loginData.authorization != "0";
    // return true;
  }

  getAutorization() {
    return this._loginData.authorization;
  }

  checkIsVisitor() {
    return this._loginData.loginType == Constants.LOGIN_TYPE.VISITOR;
  }

  checkIsUser() {
    return this._loginData.loginType == Constants.LOGIN_TYPE.USER;
  }

  clearLoginData() {
    this._loginData = {};
    this.saveData();
  }

  updateAuthorization(authorization) {
    this._loginData.authorization = authorization;
    this.saveData();
  }

  updateLoginType(type) {
    this._loginData.loginType = type;
    this.saveData();
  }

  saveData() {
    this.dataManager.getModel(Constants.MODULE_TYPE.PUSH).addTag("loginType", this._loginData.loginType);
    let loginData = JSON.stringify(this._loginData);
    AsyncStorage.setItem("loginData", loginData, function(errs){
                //TODO:错误处理
                if (errs) {
                  console.log('存储loginData错误');
                }
                if (!errs) {
                  console.log('存储loginData无误');
                }
            });
  }

  //游客登录
  //http://118.89.111.124:8080/dqauth/app/visitor_login
  sendVisitorLogin(callback) {
    // this.sendPost(Config.serverUrlHttps + "/app/visitor_verify", JSON.stringify({}), callback);
    let sendData = {"client_version":Config.version_app, "os": Config.app_os};
    this.sendPostGetJson(Config.serverUrlHttps + "/app/visitor_login", JSON.stringify(sendData), callback);
  }

  //http://118.89.111.124:8080/dqauth/app/login
  // {
  //   "id": "705034240",
  //   "passwd": "taaotj8fqg",
  //   "sms_code": "fx5v1s",
  //   "type": "admin"
  // }
  sendLogin(data, callback) {
    var sendData = {
      "id": data.phoneNum + "",
      "type": data.type,
      "client_version":Config.version_app,
      "os": Config.app_os,
    }
    if(data.password) {
      sendData.passwd = data.password + "";
    }
    else if (data.smsNum) {
      sendData.sms_code = data.smsNum + "";
    }
    this.sendPostGetJson(Config.serverUrlHttps + "/app/login", JSON.stringify(sendData), callback);
  }

  //sms密码
  //type (integer): 使用类型，1登录，2注册 = ['1', '2']
  sendRequestSms(data, callback) {
    let type = parseInt(data.type);
    var sendData = {
      "id": data.phoneNum + "",
      "type": type,
    }
    //修改密码
    //http://47.93.32.102:8081/dqauth/app/passwd/sms
    if(data.type == 3 || data.type == 4) {
      this.sendPostGetJson(Config.serverUrlHttps + "/app/passwd/sms", JSON.stringify({type:data.type}), callback);
    }
    //http://47.93.32.102:8081/dqauth/app/sms
    else {
      this.sendPostGetJson(Config.serverUrlHttps + "/app/sms", JSON.stringify(sendData), callback);
    }
  }

  //http://118.89.111.124:8080/dqauth/app/register
  //http://47.93.32.102:8081/dqauth/app/register
  //注册
  // {
  //   "mobile": "26069243394",
  //   "nick": "g7",
  //   "passwd": "7bs26355df",
  //   "sms_code": "89k2yg"
  // }
  sendRegiste(data, callback) {
    var sendData = {
      "mobile": data.phoneNum,
      "nick": data.nickName,
      "passwd": data.password,
      "sms_code": data.smsNum,
      "client_version":Config.version_app,
      "os": Config.app_os,
    }
    this.sendPostGetJson(Config.serverUrlHttps + "/app/register", JSON.stringify(sendData), callback);
  }

  //http://47.93.32.102:8081/dqauth/app/verify
  //实名验证
  // {
  //   "ee_no": 59630680,
  //   "name": "7f6",
  //   "sms_code": "uftd0m"
  // }
  sendVerify(data, callback) {
    var sendData = {
      "ee_no": parseInt(data.workerNum),
      "name": data.trueName,
      "sms_code": data.smsNum + "",
    }
    this.sendPostGetJson(Config.serverUrlHttps + "/app/verify", JSON.stringify(sendData), callback);
  }

  checkVersion(actionData, callback) {
    var sendData = {
      "client_version": Config.version_app,
      "os": Config.app_os,//1 android 2 ios
    }
    this.sendPost(Config.serverUrlHttps + "/app/check", JSON.stringify(sendData),
      (data, isSucceed, response) => {this._checkVersionCallback(data, isSucceed, response, callback);}
    )
  }

  _checkVersionCallback(data, isSucceed, response, callback) {
    console.log("APP版本信息", data, isSucceed, response);
    callback && callback(data, isSucceed, response);
    if(isSucceed) {
      let update_client = data.update_client;
      if(data.pkg_url != undefined) {
        Config.app_url = data.pkg_url;
      }
      if(update_client > 0) {//是否需要更新客户端，0否，1是2强制 = ['0', '1', '2']
        let params = [
            {text:'确定', onPress:()=>{
              Linking.openURL(Config.app_url);
              if(update_client === 1) {//不是强制更新的，点了确定就进入首页
                this._setupFinish();
              }
            }}
          ];
        if(update_client == 1) {
          params.push({text:'下次提示', onPress:()=>{
            this._setupFinish();
          }});
        }
        Alert.alert('提示','您的APP版本过低\n请更新', params)
      }
      else {
        // ToastUtils.show("当前版本已经最新");
        this._setupFinish();
      }
    }
    else {
      Alert.alert('提示','APP版本检查出错请重试' + response.status)
    }
  }
}
